/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package kotionokyurievna.gmail.com.threadjoinvolatile.threadPack;

import java.util.ArrayList;

/**
 *
 * @author Kateryna_Reznik
 */
public class ThreadScheduler {
    private int threadCount;
    private int[] arrayToCalculate;
    private double sum;
    
    public ThreadScheduler( int threadCount, int[] argumentsArray){
        setThreadCount(threadCount);
        int arLength = argumentsArray.length;
        arrayToCalculate = new int[arLength];
        System.arraycopy(argumentsArray, 0, arrayToCalculate, 0, arLength);
        sum = 0;
    }
    
      
    public void setThreadCount( int threadNum){
        if ( threadNum > 0 ){
            threadCount = threadNum;
        }
        else{
            threadCount = 1;
        }
    }
    
    public double divideTask(){
        ArrayList<SimpleThread> runnablePool = new ArrayList<>();
        SimpleThread sThread;
        ArrayList<Thread> threadPool = new ArrayList<>();
        int n = arrayToCalculate.length;
        int from = 0;
        int to = 0;
        int nTasks = 0;
        int tasks[][] = new int [threadCount][];
        for ( int i = 0; i < threadCount; i++ ){
            from = i * n / threadCount;
            to = (i + 1) * n / threadCount;
            nTasks = to - from;
            tasks[i] = new int[nTasks];
            System.arraycopy(arrayToCalculate, from, tasks[i], 0, nTasks);
            sThread = new SimpleThread(tasks[i], i);
            runnablePool.add(sThread);
        }
        
        for ( SimpleThread st: runnablePool ){
            threadPool.add(new Thread( st ));
        }
        
        for ( Thread t: threadPool ){
            t.start();
        }
        
        double sum = 0;
        
        for ( int i = 0; i < threadPool.size() ; i++){
            try {
                threadPool.get(i).join();
                sum += runnablePool.get(i).getResult();
            }
            catch ( InterruptedException ex ){
                System.out.println(ex);
            }
        } 
        
        return sum;
                
    }
       
    
    public boolean equals ( Object obj ){
	if ( obj != null && getClass() == obj.getClass() ){
            ThreadScheduler other = (ThreadScheduler) obj;
            return ( other.threadCount == threadCount);
	}
	return false;
    }
}
